package com.guc.web;


import com.guc.pojo.User;
import com.guc.servces.UserServies;
import com.guc.servces.UserServiesImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理用户登陆注册请求
 */
@WebServlet(urlPatterns = "/user")
public class UserServlet extends HttpServlet {

    UserServies userServies = new UserServiesImpl();

    //处理get请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String opr = req.getParameter("opr");
        if(opr!=null&&opr.equals("adduser")){
            //用户注册
            String loginname = req.getParameter("loginname");//用户名
            String pwdname = req.getParameter("pwdname");//密码
            //调用dao层方法，进行注册（保存用户信息）
            int i = userServies.addUser(loginname, pwdname);
            if(i>0){
                //注册成功
                req.setAttribute("msg","用户注册成功");
            }else{
                //注册失败
                req.setAttribute("msg","用户注册败");
            }
            //转发到信息显示页面user.jsp
            req.getRequestDispatcher("user.jsp").forward(req,resp);

        }else if(opr!=null&&opr.equals("login")){
            //        登陆业务的逻辑
            String loginname = req.getParameter("loginname");//用户名
            String pwdname = req.getParameter("pwdname");//密码
            // 调用服务层方法，进行登录操作
            User login = userServies.login(loginname, pwdname);
            if(login!=null){
                //登陆成功
                System.out.println("登陆成功，loginname="+loginname+";pwdname="+pwdname);
                //发送数据到页面
                req.setAttribute("msg","登陆成功，loginname="+loginname+";pwdname="+pwdname);
            }else{
                //登陆失败
                System.out.println("登陆失败，loginname="+loginname+";pwdname="+pwdname);
                //发送数据到页面
                req.setAttribute("msg","登陆失败，loginname="+loginname+";pwdname="+pwdname);
            }
        }
        //转发到新的页面
        req.getRequestDispatcher("user.jsp").forward(req,resp);
    }
    //处理post请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
//    只是参考
}
